package com.codesynapse.controller;

import com.codesynapse.dto.AIRequest;
import com.codesynapse.service.AIModelService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/test")
@RequiredArgsConstructor
public class TestController {

    private final AIModelService aiModelService;

    @GetMapping("/ollama")
    public String testOllama() {
        try {
            String result = aiModelService.generateCompletion("生成一个简单的Java类");
            log.info("Ollama测试结果: {}", result);
            return "Ollama服务正常: " + result;
        } catch (Exception e) {
            log.error("Ollama测试失败", e);
            return "Ollama服务异常: " + e.getMessage();
        }
    }

    @GetMapping("/sql")
    public String testSQL() {
        String prompt = "创建一个用户表，包含以下字段：id（主键自增）、username（用户名）、email（邮箱）、created_at（创建时间）";
        return aiModelService.generateSQL(prompt);
    }

    @GetMapping("/sql/advanced")
    public String testAdvancedSQL(@RequestParam String dialect) {
        AIRequest request = new AIRequest();
        request.setDialect(dialect);
        request.setPrompt("创建一个订单表orders，包含字段：id（主键）、user_id（用户ID，外键关联users表）、" +
                "total_amount（订单总金额，decimal类型）、status（订单状态，枚举类型：pending/completed/cancelled）、" +
                "created_at（创建时间）。然后编写一个查询，统计每个用户的订单总金额，只统计已完成的订单。");
        log.info("测试高级SQL生成，方言：{}，提示：{}", dialect, request.getPrompt());
        return aiModelService.generateSQLWithDialect(request);
    }

    @GetMapping("/search")
    public String testSearch() {
        String query = "查找Java Spring Boot中用户注册的Controller代码示例，包含接收用户名和邮箱的注册接口";
        log.info("测试基础代码搜索，查询：{}", query);
        return aiModelService.searchCode(query);
    }

    @GetMapping("/search/advanced")
    public String testAdvancedSearch(
            @RequestParam String query,
            @RequestParam String language,
            @RequestParam String framework) {
        AIRequest request = new AIRequest();
        request.setPrompt(query);
        request.setLanguage(language);
        request.setFramework(framework);
        
        log.info("测试高级代码搜索，查询：{}，语言：{}，框架：{}", 
            query, language, framework);
        return aiModelService.searchCodeWithFilters(request);
    }

    @PostMapping("/analyze")
    public String testCodeAnalysis(@RequestBody CodeAnalysisRequest request) {
        log.info("测试代码分析功能，代码：{}", request.code());
        return aiModelService.analyzeCode(request.code());
    }
}

record CodeAnalysisRequest(String code) {} 